package com.ybkj.daijia.api.driver.v1;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.server.event.model.DriverUpdateLocationEvent;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.DriverService;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "driver/api/rest/v1")
public class LocationController {

    private static final Logger logger = LoggerFactory.getLogger(LocationController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    /**
     * 更新指定司机的坐标位置
     *
     * @param id
     * @param longitude
     * @param latitude
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "updateUserLocation", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport updateUserLocation(Long id, Double longitude,
        Double latitude, String appKey, String token, String timestamp) {

        logger.debug("recv id:{},Longitude:{},Latitude:{},appKey:{},token:{},timestamp:{}",
            id, longitude, latitude, appKey, token, timestamp);

        if (null == id || null == longitude || null == latitude
            || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        Driver driver = driverService.findOne(id);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(id));
        params.add(String.valueOf(longitude));
        params.add(String.valueOf(latitude));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            if (latitude > 3 && latitude < 54 && longitude > 73 && longitude < 136) {

                String address = "未知";

                Double lastLat = driver.getLastLatitude();
                Double lastLng = driver.getLastLongitude();

                if (lastLat == null || lastLng == null) {
                    lastLat = latitude;
                    lastLng = longitude;
                    address = HttpClientUtil.getPlaceByLngAndLat(longitude, latitude);//查询地址信息
                } else {
                    double distance = Distance
                        .doubleVal(latitude, longitude, driver.getLastLatitude(),
                            driver.getLastLongitude());
                    if (distance >= 0.1) {
                        lastLat = latitude;
                        lastLng = longitude;
                        address = HttpClientUtil.getPlaceByLngAndLat(longitude, latitude);//查询地址信息
                    }
                }

                driverService.updateLocation(longitude, latitude, lastLng, lastLat,
                    "未知".equals(address) ? null : address, driver.getId());

                DriverUpdateLocationEvent updateLocationEvent = new DriverUpdateLocationEvent(
                    driver, latitude, longitude, address);
                applicationEventMulticaster.multicastEvent(updateLocationEvent);

            }

            driverService.updatePosUpdated(driver.getId(), new Date());

            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS); // 更新坐标

        } catch (Exception e) {
            logger.error("api v1 driver updateUserLocation error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }
}
